package com.ccl.iot.managers;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.SystemClock;
import android.text.format.Formatter;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import com.ccl.iot.publics.Res;
import com.ccl.iot.privates.RomInfoBean;
import com.ccl.iot.privates.RomInfoBean.FirmwareEntity;
import com.ccl.iot.publics.ThreadPoolUtils;
import com.ccl.iot.App;
import com.ccl.iot.updater.HttpHelper;
import com.ccl.iot.updater.HttpHelper.HttpDownloadListener;
import com.ccl.iot.IOTCallback.UpgradeProgressCallback;
import com.ccl.iot.IOTNetAPI;
import com.ccl.iot.R;
import com.ccl.iot.device.IOTDevice;
import com.ccl.iot.object.IOTDeviceInfoEx;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RomUpgradeManager {
	public interface UpgradeProcessListener {

		public void onStartDownLoad();

		public void processDownLoad(int aTotal, int aProgress);

		public void onDownLoadSuccess();

		public void onDownLoadFail();

		public void onStartUpgrade();

		public void processUpgrade(int aTotal, int aProgress);

		public void onUpgradeSuccess();

		public void onUpgradeFail();
	}

	private static RomUpgradeManager mInstance = null;

	public static synchronized RomUpgradeManager getInstance() {
		if (mInstance == null) {
			mInstance = new RomUpgradeManager();
		}
		return mInstance;
	}

	private static Map<Long, UpgradeProcessListener> mListeners = null;
	
	public static UpgradeProcessListener getTaskListener(long id){
		if(mListeners != null){
			return mListeners.get(id);
		}
		return null;
	}

	private HashMap<Integer, RomInfoBean> mRomInfos; // 固件的信息
	private HashMap<Long, String> mCallBackInfos; // 可升级设备的id和设备的升级信息(ip和端口)
	private IOTNetAPI mApi;
	private DeviceManager mDeviceManager;
	private Context mContext;
	private int mItem;

	private RomUpgradeManager() {
		mListeners = new HashMap<Long, UpgradeProcessListener>();
		mDeviceManager = DeviceManager.GetDefaultManager();
		mApi = IOTNetAPI.GetInstance();
		mContext = App.getContext();
		initDa();
	}

	private void initDa() {
		// 获取所有固件信息
		mRomInfos = mDeviceManager.getRomInfos();
		// 获取可升级设备的ip和端口
		mCallBackInfos = mDeviceManager.getCallbackInfos();
	}

	public synchronized void addOnUpgradeProcessListener(long id, UpgradeProcessListener listener) {
		if (listener != null) {
			mListeners.put(id, listener);
		}
	}

	public synchronized void removeOnUpgradeProcessListener(UpgradeProcessListener listener) {
		mListeners.remove(listener);
	}

	public Map<Long, UpgradeProcessListener> getTaskList() {
		return mListeners;
	}

	public void upgrade(final IOTDevice dev, final int model, final boolean upgradeOne, Context context) {
		mContext = context;

		if (mRomInfos != null) {
			// 获取要升级型号的设备固件信息
			RomInfoBean romInfo = mRomInfos.get(model);
			String callBackinfo = null;
			if (dev.isReupgradeable()) {
				callBackinfo = dev.getRomUpgradeInfo();
			} else {
				callBackinfo = mCallBackInfos == null ? null : mCallBackInfos.get(dev.getID());
			}
			if (romInfo != null && callBackinfo != null) {
				AlertDialog.Builder builder = new AlertDialog.Builder(mContext, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
				// 设置对话框的标题, 如果是升级全部则标题为设备型号, 否则为设备名
				if (upgradeOne) {
					builder.setTitle(dev.getName());
				} else {
					builder.setTitle(dev.getDeviceInfo().iModel + "");
				}

				// 获取各个版本的固件信息
				List<FirmwareEntity> firmware = romInfo.Firmware;
				String firmeares = "";
				String[] names = new String[firmware.size()];
				// 格式化固件信息
				for (int i = 0; i < firmware.size(); i++) {
					firmeares += Res.GetString(mContext, R.string.DeviceFirmware) + (i + 1) + ": " + firmware.get(i).FirmwareName + ", " + Res.GetString(mContext, R.string.Caption_Size) + Formatter.formatFileSize(mContext, firmware.get(i).FileSize) + "\n";
					names[i] = firmware.get(i).FirmwareName;
				}
				String msg = Res.GetString(mContext, R.string.DeviceFirmwareVersion) + romInfo.Version + "\n" + firmeares + Res.GetString(mContext, R.string.UpdateData) + romInfo.Date + "\n" + Res.GetString(mContext, R.string.DeviceFirmwareDes) + romInfo.Description;
				builder.setMessage(msg);
				// 让用户选择固件
				Spinner spinner = new Spinner(mContext);
				ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item, names);
				adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				spinner.setAdapter(adapter);
				spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
						mItem = position;
					}

					@Override
					public void onNothingSelected(AdapterView<?> parent) {

					}
				});

				builder.setView(spinner);
				final String tmpInfo = callBackinfo;
				builder.setPositiveButton(Res.GetString(mContext, R.string.Update), new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// 开始下载升级固件
						startUpgradeUpgrade(mRomInfos.get(model), tmpInfo, dev, upgradeOne);
					}
				});
				builder.setNegativeButton(Res.GetString(mContext, R.string.Cancel), null);
				builder.show();
			}
		}
	}

	private void startUpgradeUpgrade(final RomInfoBean romInfo, String callBackInfo, final IOTDevice dev, final boolean upgradeOne) {
		// 切割得到要升级设备的ip和端口
		final String[] splitInfo = callBackInfo.split("#");
		final String url = "http://iot.cclcp.com:5499/Downloads/Firmware/CCL" + getModel(dev.getDeviceInfo().iModel) + "/" + romInfo.Firmware.get(mItem).FirmwareURL;
		final long devId = dev.getID();
		ThreadPoolUtils.getInstance().addTask(new Runnable() {

			@Override
			public void run() {
				// 开始下载
				if (upgradeOne) {
					mListeners.get(devId).onStartDownLoad();
				} else {
					for (Long id : mListeners.keySet()) {
						mListeners.get(id).onStartDownLoad();
					}
				}

				// 正在下载
				int result = HttpHelper.GetHttpRequestFile(url, GetDefaultDownloadRom(romInfo, devId), new HttpDownloadListener() {

					@Override
					public void onDownloadProgress(final int aSize, int aPos) {
						if (upgradeOne) {
							mListeners.get(devId).processDownLoad(aSize, aPos);
						} else {
							for (Long id : mListeners.keySet()) {
								mListeners.get(id).processDownLoad(aSize, aPos);
							}
						}
					}
				});

				if (result == -1) {
					// 下载失败
					if (upgradeOne) {
						mListeners.get(devId).onDownLoadFail();
					} else {
						for (Long id : mListeners.keySet()) {
							mListeners.get(id).onDownLoadFail();
						}
					}
					return;
				} else {
					// 下载成功
					if (upgradeOne) {
						mListeners.get(devId).onDownLoadSuccess();
					} else {
						for (Long id : mListeners.keySet()) {
							mListeners.get(id).onDownLoadSuccess();
						}
					}
				}

				SystemClock.sleep(1000);

				// 开始升级
				if (upgradeOne) {
					mListeners.get(devId).onStartUpgrade();
				} else {
					for (Long id : mListeners.keySet()) {
						mListeners.get(id).onStartUpgrade();
					}
				}

				IOTDeviceInfoEx deviceInfo = dev.getDeviceInfo();

				// 正在升级
				if (upgradeOne) {
					// 正在升级
					boolean result2 = mApi.upgradeOne(GetDefaultDownloadRom(romInfo, devId), (short) deviceInfo.iType, (short) deviceInfo.iModel, romInfo.Code + 10, Integer.parseInt(splitInfo[0]), Short.parseShort(splitInfo[1]), new UpgradeProgressCallback() {

						@Override
						public void onUpgradeProgressCallback(long aDevID, final int aTotal, final int aProgress) {
							mListeners.get(aDevID).processUpgrade(aTotal, aProgress);

							if (aProgress >= aTotal) {
								// 升级成功
								mListeners.get(aDevID).onUpgradeSuccess();
							}
						}

					});
					
					if(!result2){
						mListeners.get(devId).onUpgradeFail();
					}
					
				} else {

					// 全部升级
					boolean result2 = mApi.upgradeAll(GetDefaultDownloadRom(romInfo, devId), (short) deviceInfo.iType, (short) deviceInfo.iModel, romInfo.Code + 10, new UpgradeProgressCallback() {

						@Override
						public void onUpgradeProgressCallback(long aDevID, final int aTotal, final int aProgress) {
							mListeners.get(aDevID).processUpgrade(aTotal, aProgress);

							if (aProgress >= aTotal) {
								// 升级成功
								mListeners.get(aDevID).onUpgradeSuccess();
							}
						}

					});
					
					if(!result2){
						mListeners.get(devId).onUpgradeFail();
					}
				}

				// 删除下载的固件
				File file = new File(GetDefaultDownloadRom(romInfo, devId));
				if (file.exists()) {
					file.delete();
				}
			}
		});

	}

	private String getModel(int model) {
		if (model == 55132) {
			return "55d1";
		} else {
			return model + "";
		}
	}

	/**
	 * 获取默认的固件存放路径
	 * @param mRomInfo
	 * @return
	 */
	private String GetDefaultDownloadRom(RomInfoBean mRomInfo, long id) {
		if (mContext != null && mRomInfo != null) {
			return mContext.getExternalCacheDir().getAbsolutePath() + "/firmware" + "-" + id + ".bin";
		}
		return null;
	}
}
